// Copyright (c) 2024, the WwMusic project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package com.springfairy.config;


import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 拦截器
 */
public class LoginInterceptor  implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        HttpSession session = request.getSession(false); // 不创建新 session
        if (session == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录：无session");
            return false;
        }

        Object userId = session.getAttribute("userId");
        Object tokenInSession = session.getAttribute("token");

        if (userId == null || tokenInSession == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录：Session为空");
            return false;
        }

        // 从 cookie 中读取 token
        String tokenInCookie = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    tokenInCookie = cookie.getValue();
                    break;
                }
            }
        }

        if (tokenInCookie == null || !tokenInCookie.equals(tokenInSession)) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录：Token 不匹配");
            return false;
        }
        // 通过验证
        return true;
    }
}
